import { Context, Next } from 'koa';
import { UserToken, verifyToken, UserState } from '../utils/tokenUtil';
import { formatResponse } from '../utils/formatUtil';
import UserModel from '../models/user.model';
import RoleModel from '../models/role.model';
import { Op } from 'sequelize';
import PermissionModel from '../models/permission.model';

/**
 * 检查用户权限
 * @param {string} permission - 要检查的权限
 */
const checkPermission = (permission: string) => {
  return async (ctx: Context, next: Next) => {
    const token = ctx.headers['authorization']?.split(' ')[1]; // 从请求头中获取 token
    if (!token) {
      ctx.status = 401;
      ctx.body = formatResponse(null, '未提供token', 401);
      return;
    }

    const userState = verifyToken(token) as UserToken; // 校验 token
    // 获取用户权限列表
    const user = await UserModel.findOne({
      where: { id: userState.id },
      include: [{ model: RoleModel }],
    });
    if (!user || user.isDeleted) {
      ctx.status = 401;
      ctx.body = formatResponse(null, '用户不存在或已被禁用', 401);
      return;
    }

    const rolesIds = user.roles?.map((item) => item.id);
    const roles = await RoleModel.findAll({ where: { id: { [Op.in]: rolesIds } }, include: [{ model: PermissionModel }] });

    const userPermissions = roles.flatMap((item) => item.permissions?.map((item) => item.code));

    if (!userPermissions?.includes(permission)) {
      ctx.status = 403; // 禁止访问
      ctx.body = formatResponse(null, '没有访问权限，请联系管理员', 403);
      return;
    }

    ctx.state.userState = {
      userId: user.id,
      isAdmin: roles.some((item) => item.name === '管理员'),
    } as UserState; // 将用户信息存储在 ctx.state 中
    await next(); // 继续执行下一个中间件
  };
};

export default checkPermission;
